package com.countertack.impala;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ImpalaConnector {

	private Connection con;

	private static ImpalaConnector iConnector = null;

	public ImpalaConnector() {

	}

	public static ImpalaConnector createImpalaConnectorInstance(String host) {

		if (iConnector == null) {

			iConnector = new ImpalaConnector();

			iConnector.createImpalaConnection(host);

		}

		return iConnector;

	}

	public void createImpalaConnection(String host) {

		try {
			Class.forName("org.apache.hive.jdbc.HiveDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}
		System.out.println("Connecting...");
		try {

			con = DriverManager.getConnection("jdbc:hive2://" + host
					+ ":21050/;auth=noSasl");
			// 21050

			System.out.println("Success fully connected to Impala");

		} catch (Exception e) {

			System.out.println("unable to connect");
			e.printStackTrace();
		}

	}

	public ResultSet executeQueryAndReturnResults(String query) {
		System.out.println(query);
		Statement stmt = null;
		ResultSet res = null;
		try {

			stmt = con.createStatement();

			res = stmt.executeQuery(query);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (stmt != null) {

				// try {
				// //stmt.close();
				// } catch (SQLException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }

			}
		}
		return res;

	}

	public void closeImpalaConnection() {

		try {
			if (con != null) {

				con.close();

			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {

		ImpalaConnector i = ImpalaConnector
				.createImpalaConnectorInstance("s17.dev.countertack.com");

	}

}